/**
 * 位 - 循环️ 左右 位移
 * xIndex > 0 左位移
 * xIndex < 0 右位移
 * str  ： 需要移动的目标字符
 * shift.continued : 是否持续移动
 */
class Shift {
  constructor(str) {
    this.continued = false

    this.buf = Buffer.from(str.toString())
    this.byteLength = this.buf.length
    this.bitLength = this.byteLength * 8

    this.resBuf = Buffer.alloc(this.byteLength)
  }
  // 循环位移
  cyclicShift(xIndex) {
    this.byteCyclicShift(xIndex)
  }
  // 字节-循环位移
  byteCyclicShift(xIndex) {
    let absIndex = xIndex > 0 ? xIndex : ~xIndex + 1

    if (absIndex > this.byteLength) {
      console.log('长度超出！')
    } else if (absIndex === this.byteLength || !absIndex) {
      this.buf.copy(this.resBuf)
    } else {
      // 左右位移-区别和总长度有关
      xIndex = xIndex > 0 ? xIndex : this.byteLength + xIndex

      this.buf.copy(this.resBuf, 0, xIndex, this.byteLength)
      this.buf.copy(this.resBuf, this.byteLength - xIndex, 0, xIndex)

      this.continued && this.resBuf.copy(this.buf)
    }
  }

  // 位-循环位移
  bitCyclicShift(xIndex) {
    if (xIndex < 0) {
      console.log('输入不规范！')
    } else if (xIndex > this.bitLength) {
      console.log('长度超出！')
    } else if (xIndex === this.bitLength || !xIndex) {
      this.buf.copy(this.resBuf)
    } else {
      this.bitMove(xIndex)
    }
  }

  // fn
  bitMove(xIndex) {
    let left = this
  }
}

let shift = new Shift(1234567890)
shift.continued = true

shift.cyclicShift(5)
console.log(shift.buf)
console.log(shift.resBuf.toString('ascii'))
shift.cyclicShift(-8)
console.log(shift.buf)
console.log(shift.resBuf.toString('ascii'))
